<style scoped>
    .links{
			stroke:steelblue;
	}
    .d3-svg{
        height: 750px;
        width: 100%;
    }
</style>
<style>
.links{
	stroke:#A5ABB6;
}
.reltext{
    font-size:12px;
    background: rgba(0,0,0,0);
}
.d3-svg > svg .node{
    cursor: pointer;
}
.d3-svg > svg .text_g{
    background: rgba(0,0,0,0);
}
.demo-breadcrumb-separator{
        color: #ff5500;
        padding: 0 5px;
    }
    .inb{
        display: inline;
        cursor: pointer;
    }
</style>

<template>
    <div class="team-relationship">
        <product-title></product-title>
        <Row>
            <Col span="23" offset="1">
                <Breadcrumb separator="<b class='demo-breadcrumb-separator'>=></b>">
                    <div class="inb" @click="toName(index)" v-for="(item,index) in datalevel"  :key="item.name">
                        <BreadcrumbItem >{{item.name}}</BreadcrumbItem>
                    </div>
                </Breadcrumb>
            </Col>
        </Row>       
        <div class="d3-svg" id="d3-svg" ref="d3svg">
           
        </div>  
    </div>
</template>

<script>
   import productTitle from '../../components/productTitle'
   //import { getAgentRelation } from '../../api/team';
   //import { getAgentRelation } from '../../api/employee';
   import * as d3 from "d3"
   export default {
       data(){
           return {
                datalevel:[
                    
                ],
                svgWidth:0,
                svgHeight:0,
                nodes: [
                    
                
                ],
                links: [
                                      
                ]
           }
       },
       components:{
           productTitle
       },
       computed: {
         getuid(){
             return this.$store.state.user.id
         }  
       },
       mounted () {
           //console.log(this.$refs.d3svg.getBoundingClientRect().width)
           this.svgWidth = this.$refs.d3svg.getBoundingClientRect().width
           this.svgHeight = this.$refs.d3svg.getBoundingClientRect().height-20
           //this.createSvg();
           this.getData() ;             
                            
       },
       watch: {
            '$route' (to, from) {
            // 对路由变化作出响应...
            this.datalevel=[];
            this.getData() ; 
            }
        },
       methods:{

           toName(index) {
               console.log(index);
               
               this.nodes = this.datalevel[index].nodes
               this.links = this.datalevel[index].links
               this.createSvg();
               var _length = this.datalevel.length - index - 1;
               if(_length > 0){
                   this.datalevel.splice(index+1,_length)
               }
               
           },
           //获取数据
        getData(id) {
            let _params={
                uid:this.getuid
            }
            if(id){
                _params.uid = id
            }
        //    new Promise((resolve, reject) => {
        //         getAgentRelation(_params).then(response => {
        //             if (response.data.err == 0) {
        //                 //console.log(response.data)
        //                 if(response.data.data.links.length > 0){
        //                     this.nodes = response.data.data.nodes;
        //                     this.links = response.data.data.links;
        //                     var _name = response.data.data.firstName;
        //                     var _obj = {}
        //                     _obj.name = _name
        //                     _obj.nodes = response.data.data.nodes
        //                     _obj.links = response.data.data.links
        //                     this.datalevel.push(_obj)
        //                     console.log(this.datalevel)
        //                     this.createSvg();
        //                 }else{
        //                     this.$Message.error("没有数据了");
        //                 }                        
        //             } else {
        //                 this.$Message.error(response.data.info);
        //             }
        //             resolve();
        //         }).catch(error => {
        //             reject(error);
        //         });
        //     });
        },
        createSvg() {
            var _this = this;
            var zoom = d3.zoom()
                            .scaleExtent([0.2,10])
                            .on("zoom",zoomed);
            d3.select("#wrapsvg").remove();                  
            var svg = d3.select("#d3-svg").append("svg")
                                            .attr("height", this.svgHeight)
                                            .attr("width", this.svgWidth)
                                            .attr("id","wrapsvg");
            //svg.selectAll().remove();
            svg = svg.append("svg:g").attr("width",this.svgWidth-50)
					.attr("height",this.svgHeight-50)
                    .attr("class","all").call(zoom);
       
            function zoomed(){
                d3.select(this).attr("transform", d3.event.transform);
            }
            var jt =  svg.append("svg:defs").selectAll("marker")
                        .data(["end"])
                        .enter().append("svg:marker")
                        .attr("id","arrow")
                        .attr('class','arrow')
                        .attr("viewBox", "0 -5 10 10")
                        .attr("refX", 10)
                        .attr("refY", 0)
                        .attr("markerWidth", 9)
                        .attr("markerHeight", 16)
                        .attr("markerUnits","userSpaceOnUse")
                        .attr("orient", "auto")
                        .append("svg:path")
                        .attr("d", "M0,-5L10,0L0,5")
                        .attr('fill','#666');
            var simulation = d3.forceSimulation()
								.nodes(this.nodes)
								.force("link",d3.forceLink(this.links).distance(300))   //.id(function(d) { return d.id; })
								.force("charge",d3.forceManyBody())
								.force("center",d3.forceCenter(this.svgWidth/2,this.svgHeight/2))
								.force("collide",d3.forceCollide(60).strength(0.2).iterations(5));
				//simulation.restart();	
				console.log(this.nodes);
				console.log(this.links);
            var nodeDrag = d3.drag()
                        .on("start", dragstarted)
                        .on("drag", dragged)
                        .on("end", dragended);

            function dragstarted(d) {
            if (!d3.event.active) simulation.alphaTarget(0.3).restart();
            d.fx = d.x;
            d.fy = d.y;
            }

            function dragged(d) {
            d.fx = d3.event.x;
            d.fy = d3.event.y;
            }

            function dragended(d) {
            if (!d3.event.active) simulation.alphaTarget(0);
            d.fx = null;
            d.fy = null;
            }	
        
            //绘制元素						
            var _node = svg.selectAll("g.node")
                .data(this.nodes)
                .enter().append("svg:g")
                .attr("class", "node")
                .call(nodeDrag)
                .on('click',function(d){
                    if(d.index !== 0){
                        _this.getData(d.uid);
                    }                       
                        d3.event.stopPropagation();
                })
            //绘制元素的圆
            _node.append("circle")
                    .attr("r",25)
                    .attr("fill","#68BDF6")     
                    .attr("stroke","#5CA8DB")
                    .attr("stroke-width","2px");
            //
            _node.append("text").attr("class", "nodetext")
                    .attr("dy", "5px")
                    .attr('text-anchor','middle')
                    .attr("fill","#fff")  
                    .text(function(d) { return d.name })

            var g = svg.append("g").attr("class", "force_g"),
				R = 30;
				
			//绘制线	
            var edges_g = g
                .selectAll("g.edges").data(this.links).enter().append("svg:g").attr("class", "edges");

            var paths = edges_g.append("path").attr("class","links")
                            .attr("d", function(d){return  (  "M"+R+","+0+" L"+getDis(d.source,d.target)+",0") } )
                            .style("marker-end","url(#arrow)")
            var rect_g = edges_g.append("g").attr("class","rect_g"),
                text_g = edges_g.append("g").attr("class","text_g");	
            var text = text_g.append("text")
                        .attr("class","reltext")
                        .attr("x",function(d){ return (getDis(d.source,d.target)/2) })
                        .attr("y",0).attr("dy",".3em").attr("text-anchor","middle").text(function(d){ return d.relation });
            var bbox = text.node().getBBox();
            
            rect_g.append("rect").attr("x",bbox.x-5)
                        .attr("y",bbox.y)
                        .attr("width",bbox.width+10)
                        .attr("height",bbox.height)
                        .attr("fill","white")
                        //.attr("opacity", 0 )
				

            function getDis(s,t){
                return Math.sqrt((s.x-t.x)*(s.x-t.x)+(s.y-t.y)*(s.y-t.y));
            }
            function getTransform(source, target, _dis) {
                var r;
                if (target.x > source.x) {
                    if (target.y > source.y) {
                        r = Math.asin((target.y - source.y) / _dis)
                    } else {
                        r = Math.asin((source.y - target.y) / _dis)
                        r = -r;
                    }
        
                } else {
                    if (target.y > source.y) {
                        r = Math.asin((target.y - source.y) / _dis)
                        r = Math.PI - r;
                    } else {
                        r = Math.asin((source.y - target.y) / _dis)
                        r -= Math.PI;
                    }
                }
                r = r * (180 / Math.PI);
                return "translate(" + source.x + "," + source.y + ")rotate(" + r + ")"
            }
        
            function ticked(){

                _node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })	

              // paths.attr("d",function(d){return ("M"+R+","+0+" L"+  (getDis(d.source,d.target)-R) +",0")})
       
                edges_g.merge(edges_g).each(function(d){
                    d3.select(this).select("path")
                        .attr("d","M"+R+","+0+" L"+(getDis(d.source,d.target)-R)+",0")
                    var text = d3.select(this).select("text").attr("x",getDis(d.source,d.target)/2);
                    var bbox = text.node().getBBox();
        
                    d3.select(this).select("rect").attr("x",bbox.x-5)
                })
                edges_g.attr("transform", (d) => {
                    return getTransform(d.source,d.target,getDis(d.source,d.target))
                })	

            }
            simulation.on("tick",ticked)
        
        
        }

       }
   }
</script>
